package cn.edu.sjtu.se.dslab.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import cn.edu.sjtu.se.dslab.action.bean.PageBean;
import cn.edu.sjtu.se.dslab.component.aadl.AADLTemplate;
import cn.edu.sjtu.se.dslab.dao.IBaseDao;
import cn.edu.sjtu.se.dslab.dao.IProjectDao;
import cn.edu.sjtu.se.dslab.project.PGroup;
import cn.edu.sjtu.se.dslab.project.Project;
import cn.edu.sjtu.se.dslab.util.Const;


@Repository("projectDao")
public class ProjectDaoImpl implements IProjectDao {
	
	@Resource(name = "baseDao")
	private IBaseDao<Project> baseDao;
	
	@Override
	public Project queryById(long id) {
		return baseDao.queryById(Project.class, id);
	}

	@Override
	public Project queryByUri(String uri) {
		StringBuffer hql = new StringBuffer();
		hql.append("from Project where uri='");
		hql.append(uri);
		hql.append("'");
		return baseDao.queryObject(hql.toString());
	}

	@Override
	public void save(Project project) {
		baseDao.save(project);
	}

	@Override
	public Project update(Project project) {
		return baseDao.update(project);
	}

	@Override
	public List<Project> queryByList() {
		//the name of the class, the first letter must be uppercase
		return baseDao.queryList("Project");
	}

	@Override
	public List<Project> queryDesignPatternCategoryByUserId(long userId) {
		StringBuffer hql = new StringBuffer();
		hql.append("from Project where owner.id ='");
		hql.append(userId);
		hql.append("' and template = true");
		return baseDao.query(hql.toString());
	}

	@Override
	public List<Project> queryDesignPatternCategoryByList() {
		String hql = "from Project where template = true and deleted = 0";
		return baseDao.query(hql);
	}

	@Override
	public List<Project> queryDesignPatternCategoryByAttr(int pageNum, String name, String description, long groupId) {
		StringBuffer hql = new StringBuffer();
		hql.append("from Project p where template = true and deleted = 0");
		if (name != null && !name.equals("")) {
			hql.append(" and p.name like '%" + name.trim() + "%' ");
		}
		if (description != null && !description.equals("")) {
			hql.append(" and p.description like '%" + description.trim() + "%'");
		}
		if (groupId != 0) {
			hql.append(" and p.pgroup.id =" + groupId + " ");
		}
		//PageBean<AADLTemplate> bean = baseDao.queryByspecialHqlForPage(pageNo,
		//		Const.PAGESIZE, hql.toString());
		return baseDao.query(hql.toString());
	}
	
	@Override
	public List<Project> queryValidProjects() {
		StringBuffer hql = new StringBuffer();
		hql.append("from Project where deleted = 0");
		return baseDao.query(hql.toString());
	}

}
